package com.yunji.ylexpiration_backstage.service.impl;

import com.yunji.ylexpiration_backstage.entity.FurnAdmin;
import com.yunji.ylexpiration_backstage.entity.FurnAdminExample;
import com.yunji.ylexpiration_backstage.mapper.FurnAdminMapper;
import com.yunji.ylexpiration_backstage.service.FurnAdminService;
import com.yunji.ylexpiration_backstage.util.IPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;

@Service
public class FurnAdminServiceImpl implements FurnAdminService {

    @Autowired
    private FurnAdminMapper furnAdminMapper;

    @Override
    public FurnAdmin login(FurnAdmin furnAdmin, HttpServletRequest request, HttpSession session) {
        Object admin = session.getAttribute("admin");
        if(admin==null) {
            FurnAdminExample example = new FurnAdminExample();
            FurnAdminExample.Criteria criteria = example.createCriteria();
            criteria.andAdminNameEqualTo(furnAdmin.getAdminName());
            List<FurnAdmin> furnAdmins = furnAdminMapper.selectByExample(example);
            if (furnAdmins == null || furnAdmins.size() == 0) {
                return null;
            }
            FurnAdmin furnAdmin1 = furnAdmins.get(0);
            if (!furnAdmin.getAdminPassword().equals(furnAdmin1.getAdminPassword())) {
                return null;
            }
            furnAdmin1.setAdminPassword("");

            //登录次数+1
            FurnAdmin furnAdmin2 = new FurnAdmin();
            Date date = new Date();
            //获取当前时间
            java.sql.Timestamp date3 = new java.sql.Timestamp(date.getTime());//年 月 日 时 分 秒 毫秒
            if (furnAdmin1.getTodayData() != null) {
                furnAdmin2.setLastData(furnAdmin1.getTodayData());
            }

            //获取当前ip

            String ip = IPUtils.getIpAddr(request);
            if (furnAdmin1.getTodatyIp() != null) {
                furnAdmin2.setLastIp(furnAdmin1.getTodatyIp());
            }
            furnAdmin2.setTodatyIp(ip);
            furnAdmin2.setTodayData(date3);
            furnAdmin2.setId(furnAdmin1.getId());
            furnAdmin2.setLoginNum(furnAdmin1.getLoginNum() + 1);
            int i = furnAdminMapper.updateByPrimaryKeySelective(furnAdmin2);
            if (i == 0) {
                return null;
            }
            return furnAdmin1;
        }else{
            return null;
        }

    }
}
